from pymodbus.client.tcp import ModbusTcpClient
import logging

# 配置日志记录，包括时间戳和详细级别
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
log = logging.getLogger(__name__)

def read_holding_registers(client, address, count):
    try:
        result = client.read_holding_registers(address, count)
        if result.isError():
            log.error("读取保持寄存器时出错：%s", result)
            return None
        else:
            log.info("读取到的保持寄存器值（16位无符号整数）：%s", result.registers)
            return result.registers
    except Exception as e:
        log.exception("读取保持寄存器时发生异常：%s", e)
        return None

def main(ip, port,
         discrete_input_start, discrete_input_count,
         start, count,
         input_register_start, input_register_count):
    try:
        with ModbusTcpClient(ip, port=port) as client:
            if not client.connect():
                log.error("无法连接到Modbus服务器")
                return

                # 调用各个读取函数

            read_discrete_inputs(client, discrete_input_start, discrete_input_count)
            read_holding_registers(client, start, count)
            read_input_registers(client, input_register_start, input_register_count)

    except Exception as e:
        log.exception("主函数中发生异常：%s", e)

    # 调用主函数，传递必要的参数


# 替换为你的Modbus服务器IP、端口以及各类型寄存器的起始地址和读取数量
main('127.0.0.1', 502,
     0, 5,  # 离散输入寄存器
     0, 10,  # 保持寄存器
     0, 10)  # 输入寄存器